var packageName
let clueId
let videoId
let count = 0
let reviewList = []
let DYList = []
let xhsList = []
let spList = []
let KSList = []
if(global.WEB_PARAMS.arr){
    DYList = global.WEB_PARAMS.arr[0]
    KSList = global.WEB_PARAMS.arr[1]
    xhsList = global.WEB_PARAMS.arr[2]
    spList = global.WEB_PARAMS.arr[3]
}
console.log(DYList);
console.log(KSList);
console.log(xhsList);
console.log(spList);
function DouYin (){
packageName = 'com.ss.android.ugc.aweme'

// 打开视频App
launch(packageName);
toast('打开抖音')

// App加载完成
waitForPackage(packageName);
toast('加载完成')
sleep(8000)

// 点击消息
if(text("以后再说").className("android.widget.TextView").depth("7").drawingOrder("1").findOne(1000)){
    text("以后再说").className("android.widget.TextView").depth("7").drawingOrder("1").click() 
}
const xx = className("android.widget.TextView").depth("19").drawingOrder("1").text("消息").findOne(1000)
if(xx){
    log('找到消息')
    click(xx.bounds().centerX(),xx.bounds().centerY())
}else{
    toast('没找到消息');
    console.log('没找到消息');
    back()
}
sleep(random(1000,3000))

// 创建线索
addClue()
console.log('clueid' + clueId);

// 抓取评论
river()
}

while(true){
    // 如果勾选了抖音则执行
    if((global.WEB_PARAMS.plat&&global.WEB_PARAMS.plat.includes(1))||(DYList.length>0)){
        toastLog('执行抖音')
        DouYin()
    }
    // 如果勾选了快手则执行
    if(global.WEB_PARAMS.KuaiShouRecoverChecked||global.WEB_PARAMS.KuaiShouRiverChecked){

    }
    // 如果勾选了小红书则执行
    if(global.WEB_PARAMS.xHongShuRecoverChecked||global.WEB_PARAMS.xHongShuRiverChecked){
        hongShu()
        console.log('小红书执行完毕');
        sleep(random(1000,3000))
    }
    // 如果勾选了视频号则执行
    if(global.WEB_PARAMS.spHaoRecoverChecked||global.WEB_PARAMS.spHaoRiverChecked){
      weChat()
    }
}


// 创建线索
function addClue (){
    const res1 = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/saveClue',{
        clueName:getTime() + '线索信息',
        storeId:88888888,
        clueTime:Date.now()
        })
    clueId = res1.body.json().clueId
    console.log('线索创建成功' + clueId);
}

function getTime (){
    let now = new Date();
    let year = now.getFullYear();
    let month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
    let day = String(now.getDate()).padStart(2, '0');
    let formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
}

function river () {
    className("android.widget.Button").desc("搜索").depth("18").drawingOrder("1").findOne(1000).click()
    if(global.WEB_PARAMS.keyword){
        className("android.widget.EditText").depth("6").drawingOrder("3").text("搜索").findOne().setText(global.WEB_PARAMS.keyword)
        sleep(random(1000,3000))
        const serch = text("视频、用户、音乐、话题、地点等").drawingOrder("5").findOne(3000)
        if(serch){
            toast('找到搜索')
        }
        click(serch.bounds().centerX(), serch.bounds().centerY())
        sleep(random(3000,5000))
        const shiPinBtnDY = className('android.widget.Button').text('视频').findOne(2000)
        click(shiPinBtnDY.bounds().centerX(), shiPinBtnDY.bounds().centerY())
        sleep(3000)
        const itemDouYin = className('android.widget.FrameLayout').depth(19).findOne(2000)
        click(itemDouYin.bounds().centerX(), itemDouYin.bounds().centerY())
        sleep(random(3000,5000))
        findKeyword()
    }else{
        DYList.forEach(e=>{
            className("android.widget.EditText").depth("6").drawingOrder("3").text("搜索").findOne().setText(e.account)
            sleep(random(1000,3000))
            const serch = text("视频、用户、音乐、话题、地点等").drawingOrder("5").findOne(3000)
            if(serch){
                toast('找到搜索')
            }
            click(serch.bounds().centerX(), serch.bounds().centerY())
            sleep(random(3000,5000))
            const user = className("android.widget.Button").text("用户").depth("16").findOne(1000)
            click(user.bounds().centerX(), user.bounds().centerY())
            sleep(random(1000,2000))
            const userHao = className("com.lynx.tasm.behavior.ui.LynxFlattenUI").depth("19").drawingOrder("1").findOne(2000)
            if(userHao){
                toastLog('找到用户')
                // console.log(userHao.child(0).text());
                click(userHao.bounds().centerX(), userHao.bounds().centerY())
                sleep(random(2000,3000))
                className("android.view.View").depth("12").drawingOrder("1").findOne(2000).click()
                sleep(random(1000,3000))
                three()
            }else{
                toastLog('没有找到用户')
            }
        })
    }
    
}

function findKeyword () {
    const guangGaoDY = className("android.widget.TextView").depth("24").drawingOrder("1").text('广告').findOne(2000)
    if(!guangGaoDY&&!zhiBo){
      const keywordNameDY = className("android.widget.TextView").depth('22').drawingOrder('3').desc('按钮').findOne(2000) 
      const keywordDayDY = className("android.widget.TextView").depth('26').drawingOrder('1').findOne(2000) 
      const keywordTitle = id('desc').className("android.widget.TextView").depth("24").drawingOrder("1").findOne(2000)
      console.log(keywordNameDY&&keywordNameDY.text());
      console.log(keywordDayDY&&keywordDayDY.text());
      console.log(keywordTitle&&keywordTitle.text());
      const res = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/addVideo',{
      videoName: keywordTitle?removeSpecialCharsAndEmojis(keywordTitle.text()):'无标题',
      videoAuthor:keywordNameDY?removeSpecialCharsAndEmojis(keywordNameDY.text()):'无作者',
      videoTime:keywordDayDY?keywordDayDY.text().split(' ')[2]:'无发布时间',
      clueId: clueId,
      videoSourceState: 1,
      })
      const videoRes = res.body.json()
      console.log(videoRes);
      videoId = videoRes.videoId
      
      if(videoId){
      console.log('视频创建成功' + videoId);
      const pingLun = className("android.widget.LinearLayout").depth('21').drawingOrder('1').find()
      if(pingLun[1]){
          if(pingLun[1].child(1).child(0).text()=="评论"){
              toast('没有评论')
              swipe(
                  device.width / 2,
                  device.height * 0.8,
                  device.width / 2,
                  device.height * 0.2,
                  random(500,1000)
              )
              findKeyword()
          }else{
              pingLun[1].click()
              jieLiuKeyword()
              sleep(random(1000,2000))
              swipe(
                device.width / 2,
                device.height * 0.8,
                device.width / 2,
                device.height * 0.2,
                random(500,1000)
              )
              findKeyword()
            }
      }
        }else{
            console.log('视频重复' + videoId);
        }
    }
        
    swipe(
      device.width / 2,
      device.height * 0.8,
      device.width / 2,
      0,
      random(500,1000)
    )
    const zhiBo = className("android.widget.TextView").text('自动进入直播间').findOne(2000)
    if(zhiBo){
        swipe(
            device.width / 2,
            device.height * 0.8,
            device.width / 2,
            0,
            random(500,1000)
          )
    }
    sleep(random(1000,2000))
    findKeyword()
}
function jieLiuKeyword(){
    sleep(random(2000,3000))
    const list = className("android.widget.TextView").depth("15").drawingOrder("27").find()
    const arr = []
    list.forEach(e=>{
        arr.push(e.parent().child(1).bounds().height())
    })
    list.forEach(e=>{
        // 筛选掉最后一个
        sleep(random(2000,3000))
        if(e.parent().child(1).bounds().height() < findMax(arr)) return
        if(!e.parent().child(4).childCount()) return
        // 评论
        console.log(e.parent().child(2).text());
        console.log(e.parent().child(4).child(0).text());
        console.log(e.text());
        const remarkText = e.text()
        const remarkTime = e.parent().child(4).child(0).text()
        const userName = e.parent().child(2).text()
        click(e.parent().child(1).bounds().centerX(), e.parent().child(1).bounds().centerY())
        sleep(random(2000,3000))
        const DouYinHao = className("android.widget.TextView").depth("12").drawingOrder("2").findOne(2000)
        let IPDouYin = className("android.widget.TextView").depth("12").find()
        IPDouYin = IPDouYin.filter(e=>e.text().includes('IP'))
        if(DouYinHao&&IPDouYin.length){
          console.log(DouYinHao.text());
          console.log(IPDouYin[0].text()); 
        }
        back()
        count++
        console.log('时间戳' + Date.now());
        reviewList.push({
          remarkText:remarkText,
          remarkDYH:DouYinHao?DouYinHao.text():'',
          remarkTime:remarkTime,
          remarkSXState:"2",
          videoId:videoId,
          clueId:clueId,
          userName:userName,
          remarkIp:IPDouYin.length?IPDouYin[0].text():'',
          remarkNowTime:Date.now()
        })
        if(count>=10){
            console.log('请求');
            console.log(reviewList);
          const res = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/saveRemark',reviewList)
          count = 0
          reviewList = []
        }
        sleep(random(1000,3000))
        
    })
    if(className("android.widget.TextView").depth("14").drawingOrder("2").text("暂时没有更多了").findOne(2000)||className('android.widget.TextView').text('已折叠部分评论').findOne(2000)){
        toast('没有评论了')
        count = 0
        if(reviewList.length){
            console.log('最后一次请求');
          const res = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/saveRemark',reviewList)
          reviewList = []
        }
        back()
        swipe(
            device.width / 2,
            device.height * 0.8,
            device.width / 2,
            device.height * 0.2,
            1000
          )
    }else{
        const PingLunBox = className("android.widget.FrameLayout").depth("6").drawingOrder("2").findOne(2000)
        swipe(
          device.width / 2,
          device.height * 0.8,
          device.width / 2,
          device.height * 0.2,
          random(1000,2000)
        )
        jieLiuKeyword()
    }
  }

function three() {
    let FaBuTime
    sleep(random(1000,3000))
    let videoTimeList = className("android.widget.TextView").depth("23").drawingOrder("1").find()
    videoTimeList = videoTimeList.filter(e=>{
        return e.text().includes('IP属地')
    })
    let videoTime = videoTimeList[0].text()
    videoTime = videoTime.split('I')
    const keywordNameDY = className("android.widget.TextView").depth('22').drawingOrder('3').desc('按钮').findOne(2000) 
    const keywordTitle = id('desc').className("android.widget.TextView").depth("24").drawingOrder("1").findOne(2000)
    console.log(keywordNameDY&&keywordNameDY.text());
    console.log(keywordTitle&&keywordTitle.text());
    const res = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/addVideo',{
        videoName: keywordTitle?removeSpecialCharsAndEmojis(keywordTitle.text()):'无标题',
        videoAuthor:keywordNameDY?removeSpecialCharsAndEmojis(keywordNameDY.text()):'无作者',
        videoTime:videoTime[0]||'无发布时间',
        clueId: clueId,
        videoSourceState: 2,
    })
        console.log(res.body.json());
        videoId = res.body.json().videoId
        if(videoId){
            console.log('视频创建成功' + videoId);
            // 全屏
            const x = className("android.widget.FrameLayout").depth("0").drawingOrder("0").findOne(1000)
                if(videoTime[0].trim() == FaBuTime){
                    toastLog('没有视频了')
                    console.log('时间');
                    console.log(FaBuTime);
                    back()
                    sleep(random(1000,3000))
                    back()
                    sleep(random(1000,3000))
                    back()
                    return
                }else{
                    console.log('不是最后一个视频');
                    FaBuTime = videoTime[0].trim()
                }
                toast('视频时间在三天内')
                const pingLun = className("android.widget.LinearLayout").depth('21').drawingOrder('1').find()
                if(pingLun[1]){
                    if(pingLun[1].child(1).child(0).text()=="评论"){
                        toast('没有评论')
                        swipe(
                            device.width / 2,
                            device.height * 0.8,
                            device.width / 2,
                            device.height * 0.2,
                            random(500,1000)
                        )
                        three()
                    }else{
                        pingLun[1].click()
                        jieLiu()
                        three()
                    }
                }
        }else{
            console.log('视频重复' + videoId);
        }
        
}

function removeSpecialCharsAndEmojis(str) {
    const regex = /[^\w\s\uD834[\uDF00-\uDF5F]\uD835[\uDC00-\uDC5F]\u2600-\u26FF\u2700-\u27BF]/g;
    return str.replace(regex, '');
}

function jieLiu(){
    sleep(random(1000,3000))
    const list = className("android.widget.TextView").depth("15").drawingOrder("27").find()
    const arr = []
    list.forEach(e=>{
        arr.push(e.parent().child(1).bounds().height())
    })
    list.forEach(e=>{
        // 筛选掉头像显示不全的元素
        if(e.parent().child(1).bounds().height() < findMax(arr)) return
        // 评论
        const remarkText = e.text()
        if(e.parent().child(3).text()=='作者') return
        if(!e.parent().child(4).childCount()&&!e.parent().child(5).childCount()) return
        const remarkTime = '时间'
        if(e.parent().child(4).childCount()) remarkTime = e.parent().child(4).child(0).text()
        if(e.parent().child(5).childCount()) remarkTime = e.parent().child(5).child(0).text()
        const userName = e.parent().child(2).text()
        console.log(remarkText);
        console.log(remarkTime);
        console.log(userName);
        click(e.parent().child(1).bounds().centerX(), e.parent().child(1).bounds().centerY())
        sleep(random(2000,3000))
        const DouYinHao = className("android.widget.TextView").depth("12").drawingOrder("2").findOne(2000)
        let IPDouYin = className("android.widget.TextView").depth("12").find()
        IPDouYin = IPDouYin.filter(e=>e.text().includes('IP'))
        if(DouYinHao&&IPDouYin.length){
          console.log(DouYinHao.text());
          console.log(IPDouYin[0].text());
        }
        back()
        count++
        reviewList.push({
            remarkText:remarkText,
            remarkDYH:DouYinHao?DouYinHao.text():'',
            remarkTime:remarkTime,
            remarkSXState:"2",
            videoId:videoId,
            clueId:clueId,
            userName:userName,
            remarkIp:IPDouYin.length?IPDouYin[0].text():'',
            remarkNowTime:Date.now()
          })
          console.log(reviewList);
          console.log();
          if(count>=10){
              console.log('请求');
            const res = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/saveRemark',reviewList)
            count = 0
            reviewList = []
          }
        sleep(random(1000,3000))
    })
    if(className("android.widget.TextView").depth("14").drawingOrder("2").text("暂时没有更多了").findOne(2000)){
        toast('没有评论了')
        count = 0
        if(reviewList.length){
            console.log('最后一次请求');
          const res = http.postJson('https://www.diandianyouke.cn:8081/tuokecomment/tuoke_comment/saveRemark',reviewList)
          reviewList = []
        }
        back()
        swipe(
            device.width / 2,
            device.height * 0.8,
            device.width / 2,
            device.height * 0.2,
            random(1000,2000)
          )
    }else{
        swipe(
            device.width / 2,
            device.height * 0.8,
            device.width / 2,
            device.height * 0.2,
            random(1000,2000)
          )
        jieLiu()
    }
}

function findMax(array) {
  let max = array[0];
  for (let i = 1; i < array.length; i++) {
      if (array[i] > max) {
          max = array[i];
      }
  }
  return max;
}


// 生成随机数函数
function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

